package com.paper.tiger.easy.rpc.s.client.client;

import com.paper.tiger.easy.rpc.s.client.SpringContextSupport;
import com.paper.tiger.easy.rpc.s.client.common.Dove;
import com.paper.tiger.easy.rpc.s.client.common.LetterType;
import com.paper.tiger.easy.rpc.s.client.execute.FlyDove;
import com.paper.tiger.easy.rpc.s.client.registy.common.RegisterConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.DoubleToIntFunction;

/**
 *  心跳 handler 维持心跳,客户端发送心跳包过来,响应心跳包
 */
public class DoveClientServiceHandler extends SimpleChannelInboundHandler<Dove>
{

    /**
     * 执行具体业务的线程池
     */
    private static final ThreadPoolExecutor executor =
            new ThreadPoolExecutor(1,2,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000)
            ,new ThreadPoolExecutor.AbortPolicy());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Dove msg) throws Exception
    {
        Integer remoteType = msg.getLetterType();
        LetterType type = LetterType.getByCode(remoteType);
        // 使用策略模式，不同的策略调用不同的实现
        FlyDove service = (FlyDove) RegisterConfig.get(type.getRegisterName());

        executor.execute(()->service.service(msg,ctx));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        // 向服务器发送存根信息

        String localIp = ContextManager.getInstance().getLocalIp();
        Integer port = ContextManager.getInstance().getDoveServerPort();

        Dove dove = new Dove();
        dove.setIp(localIp);
        dove.setPort(port);
        dove.setServiceName(SpringContextSupport.getProperty("spring.application.name"));
        dove.setLetterType(LetterType.CHANNEL.getCode());
        ctx.channel().writeAndFlush(dove);
    }
}
